<script setup>
import { userUpdateInfoService } from '@/api/userinfo'
import PageContainer from '@/components/PageContainer.vue'
import { useUserStore } from '@/stores'
import { ref } from 'vue'

const { user: { id, username, nickname, email }, getUser } = useUserStore()
// 表单数据
const formModel = ref({
  id,
  username,
  nickname,
  email,
})

// 表单校验规则
const rules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { pattern: /^\S{2,10}/, message: '昵称长度在 2到10个非空字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
  ],
}

// 提交表单
function onSubmit(formEl) {
  if (!formEl)
    return
  formEl.validate(async (valid) => {
    if (valid) {
      await userUpdateInfoService(formModel.value)
      // eslint-disable-next-line no-undef
      ElMessage.success('提交成功')
      // 通知user模块，进行数据的更新
      getUser()
    }
    else {
      // eslint-disable-next-line no-undef
      ElMessage.error('请检查表单输入')
    }
  })
}
</script>

<template>
  <PageContainer title="基本资料">
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="100px">
      <el-form-item label="登录名称">
        <el-input v-model="formModel.username" disabled />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="formModel.nickname" />
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="formModel.email" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit($refs.formRef)">
          提交修改
        </el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>
